package com.lcz.jms.comsumer;

import com.alibaba.fastjson.JSON;
import com.lcz.jms.bean.MsgBean;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jms.listener.SessionAwareMessageListener;

import javax.jms.*;

/**
 * Created by luchunzhou on 2017/10/18.
 */
public class SimpleMessageListener implements SessionAwareMessageListener<Message>{

    private static final Log log = LogFactory.getLog(SimpleMessageListener.class);

    @Override
    public synchronized void onMessage(Message message, Session session) {
        try {
            ActiveMQTextMessage msg = (ActiveMQTextMessage) message;
            final String ms = msg.getText();
            log.info("==>接收的消息:" + ms);
            // 转换成相应的对象
            MsgBean msgBean = JSON.parseObject(ms, MsgBean.class);
            if (msgBean == null) {
                return;
            }
            try {
                System.out.println("消息对象："+msgBean.toString());
            } catch (Exception e) {
                // 业务异常，重新放回队列
//				activeMqJmsTemplate.send(sessionAwareQueue, new MessageCreator() {
//					public Message createMessage(Session session) throws JMSException {
//						return session.createTextMessage(ms);
//					}
//				});
                log.error("==>业务异常:", e);
            }
        } catch (Exception e) {
            log.error("==>接收消息异常", e);
        }
    }

}

//原方法如下
//public class SimpleMessageListener implements MessageListener
//    @Override
//    public void onMessage(Message message) {
//        TextMessage msg = (TextMessage) message;
//        try {
//            System.out.println("接收消息：" + msg.getText());
//        } catch (JMSException e) {
//            e.printStackTrace();
//        }
//    }
//}
